import { defineStore } from "pinia";
import { ref } from "vue";
import { signIn, logout } from "@/api/auth/login";
import { getInfo } from "@/api/system/user";

export interface StaffInfo {
  staffId: string;
  userId: string;
  deptId: string;
  staffName: string;
  staffPhone: string;
  titleId: string | null;
  positionId: string | null;
  joinDate: string;
  staffStatus: number;
  updateTime: string;
  updater: string;
  avatar: string | null;
}

export interface UserData {
  token: string | null;
  userId: string;
  username: string;
  loginTime: string | null;
  expireTime: string | null;
  ipaddr: string | null;
  permissions: string[];
  roles: string[];
}

export interface UserInfo {
  permissions: string[];
  roles: string[];
  staff: StaffInfo;
  user: UserData;
}

export const useUserStore = defineStore(
  "user",
  () => {
    const token = ref<string>("");
    const userInfo = ref<UserInfo | null>(null);
    const isLoggedIn = ref<boolean>(false);

    const setToken = (newToken: string) => {
      token.value = newToken;
      isLoggedIn.value = !!newToken;
      // 将token保存到localStorage
      if (newToken) {
        localStorage.setItem("token", newToken);
      } else {
        localStorage.removeItem("token");
      }
    };

    const setUserInfo = (info: UserInfo) => {
      userInfo.value = info;
    };

    const login = async (loginData: { username: string; password: string }) => {
      try {
        // 1. 调用登录API获取token
        const loginResponse = await signIn(loginData);
        if (loginResponse.code === 200) {
          const token = loginResponse.data;
          setToken(token);

          // 2. 获取用户信息
          const userResponse = await getInfo({ token });
          if (userResponse.code === 200) {
            setUserInfo(userResponse.data);
            return { success: true };
          } else {
            throw new Error(userResponse.msg || "获取用户信息失败");
          }
        } else {
          throw new Error(loginResponse.msg || "登录失败");
        }
      } catch (error: any) {
        return { success: false, error: error.message || "登录失败" };
      }
    };

    const logout = async () => {
      await logout();
      token.value = "";
      userInfo.value = null;
      isLoggedIn.value = false;
      localStorage.removeItem("token");
    };

    const hasPermission = (permission: string): boolean => {
      return userInfo.value?.permissions.includes(permission) || false;
    };

    const hasRole = (role: string): boolean => {
      return userInfo.value?.roles.includes(role) || false;
    };

    // 初始化时检查token
    const initAuth = async () => {
      const savedToken = localStorage.getItem("token");
      if (savedToken) {
        try {
          setToken(savedToken);
          const userResponse = await getInfo({ token: savedToken });
          if (userResponse.code === 200) {
            setUserInfo(userResponse.data);
          } else {
            // token无效，清除
            logout();
          }
        } catch (error) {
          // token无效，清除
          logout();
        }
      }
    };

    return {
      token,
      userInfo,
      isLoggedIn,
      setToken,
      setUserInfo,
      login,
      logout,
      hasPermission,
      hasRole,
      initAuth,
    };
  },
  {
    persist: true,
  }
);
